package com.filyar.htyd.utils;
import com.filyar.htyd.common.Constants;
import com.filyar.htyd.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: 非力亚-filyar
 * @Date: 2024/7/5 星期五  16:16
 * @Email: root@filyar.com
 */
@Slf4j
public class RegionUtil {

    static Searcher searcher;
    static {
        try (InputStream inputStream = RegionUtil.class.getClassLoader().getResourceAsStream("ip2region.xdb")) {
            if (inputStream == null) {
                throw new ServiceException(Constants.SYSTEM_EXCEPTION_CODE, "ip2region.xdb 文件未找到！", false);
            }
            byte[] cBuff = readAllBytes(inputStream);
            searcher = Searcher.newWithBuffer(cBuff);
        } catch (IOException e) {
            throw new ServiceException(Constants.SYSTEM_EXCEPTION_CODE, "RegionUtils初始化失败，原因：从ip2region.xdb文件加载内容失败！" + e.getMessage(), false);
        } catch (Exception e) {
            throw new ServiceException(Constants.SYSTEM_EXCEPTION_CODE, "RegionUtils初始化失败，原因：" + e.getMessage(), false);
        }
    }

    /**
     * 根据IP地址离线获取城市
     */
    public static String getCityInfo(String ip) {
        try {
            ip = ip.trim();
            // 3、执行查询
            String region = searcher.search(ip);
            return region.replace("0|", "").replace("|0", "");
        } catch (Exception e) {
            log.error("IP地址离线获取城市异常 {}", ip);
            return "未知";
        }
    }

    private static byte[] readAllBytes(InputStream inputStream) throws IOException {
        try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
            byte[] data = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, bytesRead);
            }
            return buffer.toByteArray();
        }
    }

}
